package com.jason.quectel0805.services;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.jason.quectel0805.net.IOUtils;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import androidx.annotation.NonNull;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadService extends Service {
    private ExecutorService executorService;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 100:
                    Toast.makeText(DownloadService.this, "文件成功下载，" + ((String) msg.obj), Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private static final String TAG = "jasonwan";

    public DownloadService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        executorService = Executors.newCachedThreadPool();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String downloadUrl = intent.getStringExtra("download_url");
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                startDownload(downloadUrl);
            }
        });
        return START_STICKY;
    }

    /**
     * 利用okhttp开启下载
     *
     * @param downloadUrl
     */
    private void startDownload(String downloadUrl) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(downloadUrl).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                byte[] bytes = response.body().bytes();
                String filePath = IOUtils.byteArray2File(bytes);
                Log.d(TAG, "onResponse: filePath=" + filePath);
                Message message = Message.obtain();
                message.what = 100;
                message.obj = filePath;
                handler.sendMessage(message);
            }
        });
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}